// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import router from './router'
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
import VueResource from 'vue-resource'
import CurrUser from './components/global/CurrUser'
import VueSocketIO from 'vue-socket.io'
import App from './App.vue'
import clipboard from '../static/clipboard.js'

// socket-io 连接配置
// console.log('window.ApiDoNameSocket',window.ApiDoNameSocket)
Vue.use(new VueSocketIO({
  debug: false,
  connection: ApiDoNameSocket,
  /* options: {
    path: "/socket-client-server/"        // 默认路径: /socket-io/
  } */
}))

import 'vue-area-linkage/dist/index.css' // v2 or higher
import VueAreaLinkage from 'vue-area-linkage'

Vue.use(VueAreaLinkage)
// Vue.use(VueQr)

Vue.use(ElementUI, {
  size: 'mini',
})

// import 'swiper/dist/css/swiper.css'
// Vue.use(vueSwiper)

CurrUser.checkCache()
Vue.prototype.CurrUser = CurrUser
// console.log('Vue.prototype.CurrUser', Vue.prototype.CurrUser)
Vue.prototype.demoData = {}
Vue.prototype.dict = dict

Vue.config.productionTip = false

// 接口地址
Vue.prototype.ApiDoNameAuth = ApiDoNameAuth
Vue.prototype.ApiDoNameShop = ApiDoNameShop
Vue.prototype.ApiDoNameCommon = ApiDoNameCommon
Vue.prototype.UploadFileUrl = ApiDoNameCommon + 'File/upload'
Vue.prototype.NoImageUrl = 'https://yangfan-shop.oss-cn-hangzhou.aliyuncs.com/image/no-image.jpg'
Vue.use(VueResource)
Vue.MyRequestLoading = {}

// 货币格式化方法
Vue.prototype.ToMoney = function (value) {
  return (value - 0).toFixed(2)
}

// 货币格式化方法
Vue.prototype.getIsShifu = function () {
  return localStorage.getItem('isShifu') && localStorage.getItem('isShifu') === '1'
}

/**

 * 获取屏幕宽高
 */
Vue.prototype.getWinSize = function () {
  if (localStorage.getItem('WinSize')) {
    return JSON.parse(localStorage.getItem('WinSize'))
  }
  var winSize = {
    width: window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth,
    height: window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight
  }
  localStorage.setItem('WinSize', JSON.stringify(winSize))
  return winSize
}

/**

 * 获取屏幕宽高
 */
Vue.prototype.getSafeArea = function () {
  return {
    top: 0
  }
  // localStorage.removeItem('API_SAFE_AREA')
  if (localStorage.getItem('API_SAFE_AREA')) {
    return JSON.parse(localStorage.getItem('API_SAFE_AREA'))
  }
  if (typeof api !== 'undefined' && api.safeArea && api.safeArea.top) {
    uni.getSystemInfo({
      success: function (res) {
        localStorage.setItem('API_SAFE_AREA', JSON.stringify({
          top: res.statusBarHeight
        }))
      }
    })
    return api.safeArea
  } else {
    return {
      top: 44
    }
  }
}

Vue.prototype.showImage = function (src) {
  if (!src) {
    return dict.NoImageURL
  }
  return src
}

// 应用头部信息
Vue.prototype.getHeader = function () {
  var platform=this.getPlatform()
  return {
    Authorization: 'Bearer ' + this.CurrUser.Token,
    DeviceId: Vue.prototype.GetDeviceID(),
    Platform:platform?platform:'H5',
    UserType: 'Shop'
  }
}

Vue.prototype.handlerCity = function (str) {
  // 市级省
  if (str.indexOf('省') === -1) {
    var arr1 = str.split('市')
    if (arr1.length > 1) {
      var arr2 = arr1[1].split('县')
    }
  }
}

Vue.prototype.validateMoney = (rule, value, callback) => {
  if (!value) {
    return callback(new Error('不能为空'))
  }
  setTimeout(() => {
    if (!Number.parseFloat(value)) {
      callback(new Error('请输入 数字值'))
    } else {
      if (value < 0) {
        callback(new Error('数值类型 必须大于0'))
      } else {
        callback()
      }
    }
  }, 1000)
}

Vue.prototype.checkLoginAct = function (callback) {
  let $this = this
  if ($this.CurrUser.IsLogin()) {
    callback()
    return
  }
  $this.$confirm('当前操作需要进行登录,您是否前往登录?', '系统提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    $this.$router.push('/Login')
  }).catch(() => {
  })
}

Vue.prototype.successTip = function (info, type, duration) {
  this.$message({
    offset: 70,
    center: true,
    message: info,
    type: type ? type : 'success',
    duration: duration ? duration : 1500,
  })
}

// 检查手机号码
Vue.prototype.checkMobile = function (rule, value, callback) {
  let mobileReg = /^1[3-9]\d{9}$/
  var result = value.match(mobileReg)
  if (result && result.input) {
    callback()
  } else {
    callback(new Error('手机号 格式错误!'))
  }
}
Vue.prototype.checkVerifyCode = function (rule, value, callback) {
  let mobileReg = /^\d{4,6}$/
  var result = value.match(mobileReg)
  if (result && result.input) {
    callback()
  } else {
    console.log('验证不通过')
    callback(new Error('验证码 格式错误!'))
  }
}

Vue.prototype.copyClipBoard = function (text) {
  if (typeof plus !== 'object') {
    this.$message.error('只能在App中复制')
    return
  }
  clipboard.setText(text)
}

// App解析上传文件
Vue.prototype.uploadAndParseFile=function (filePath,callback,url) {
  if (typeof plus==='undefined'){
    alert('只允许App上传文件')
  }
  if (!url){
    url=this.UploadFileUrl
  }
  let $this = this
  var wt = plus.nativeUI.showWaiting()
  var task = plus.uploader.createUpload(url,
    {method: 'POST'},
    function (returnData, status) {
      var res=JSON.parse(returnData.responseText)
      // 上传完成
      if (status === 200) {
        callback(res)
        wt.close()
      } else {
        plus.nativeUI.alert('上传失败:' + status)
        wt.close()
      }
    }
  )
  var DeviceID = $this.GetDeviceID()
  task.addFile(filePath, {key: 'myUploadFile', name: 'myUploadFile'})
  task.addData('DeviceID', DeviceID)
  task.setRequestHeader('Authorization','Bearer '+$this.CurrUser.getToken());
  task.setRequestHeader('DeviceId',$this.GetDeviceID());
  task.setRequestHeader('UserType','Member');
  task.start()
}

Vue.prototype.getScrollTop = function () {
  var scrollPos
  if (window.pageYOffset) {
    scrollPos = window.pageYOffset
  } else if (document.compatMode && document.compatMode != 'BackCompat') {
    scrollPos = document.documentElement.scrollTop
  } else if (document.body) {
    scrollPos = document.body.scrollTop
  }
  return scrollPos
}

Vue.prototype.getScrollHeight = function () {
  var scrollHeight = 0, bodyScrollHeight = 0, documentScrollHeight = 0
  if (document.body) {
    bodyScrollHeight = document.body.scrollHeight
  }
  if (document.documentElement) {
    documentScrollHeight = document.documentElement.scrollHeight
  }
  scrollHeight = (bodyScrollHeight - documentScrollHeight > 0) ? bodyScrollHeight : documentScrollHeight
  return scrollHeight
}

Vue.prototype.checkAction = function (currAction) {
  if (!localStorage.getItem('TINY_ROLE__ACTION_LIST')){
    return false
  }
  // console.log('data',localStorage.getItem('TINY_ROLE__ACTION_LIST'))
  var str = localStorage.getItem('TINY_ROLE__ACTION_LIST')
  if (str === '["*"]') {
    return true
  }
  var actionList = JSON.parse(str)
  if (!actionList){
    return false
  }
  // console.log('actionList',actionList)
  // 超级管理员

  return actionList.indexOf(currAction) > -1
}

/**
 * 通用请求方法
 * @param url 域名后的接口地址
 * @param params  参数
 * @param callback  正确-回调
 * @param errorCallback  错误-回调
 * @constructor
 */
Vue.prototype.MyRequest = function (url, params, callback, errorCallback, header, isallData) {
  var $this = this
  if (Vue.MyRequestLoading[url] === true) {
    return
  }
  if (!(url.indexOf('http://') > -1 || url.indexOf('https://') > -1)) {
    url = this.ApiDoNameShop + url
  }

  if (typeof params === 'undefined' || params === null) {
    params = {}
  }
  // params.city = this.CurrUser.City
  // params.cityCode = this.CurrUser.getCityCode()
  // params.location = this.CurrUser.Location

  // 判断header参数
  var heaerParams
  if (typeof header === 'undefined' || header === null) {
    // 默认header参数
    heaerParams = this.getHeader()
  } else {
    heaerParams = header
  }
  Vue.MyRequestLoading[url] = true
  this.$http.post(url, params, {
    emulateJSON: true,
    credentials: true,
    headers: heaerParams
  }).then(function (response) {
    Vue.MyRequestLoading[url] = false
    var res = response.data
    Vue.MyRequestAllData = res
    if (res.code > 0) {
      // 错误
      if ((res.code === 1001 && res.message === 'token 失效') || res.message==='当前店铺已经禁用') {
        CurrUser.AccessToken = ''
        CurrUser.IsLogin = false
        CurrUser.setCache(null)
        // setTimeout(function () {
        //
        // },6500)
        // $this.$router.push('/Login')
        $this.$router.push('/Login')
        return
        // location.reload()
      } else {
        // 常规错误
        if (typeof errorCallback === 'function') {
          errorCallback(res)
        } else {
          // 常规参数错误
          // console.log('常规参数错误' + JSON.stringify(res))
          // $this.$message.error(res)
        }
      }
    } else {
      // 正确回调
      if (typeof isallData !== 'undefined' && isallData === true) {
        callback(res)
      } else {
        // console.log(res.data)
        callback(res.data)
      }
    }
  }, function (errorResponse) {
    Vue.MyRequestLoading[url] = false
    console.error('--------------------------http-请求错误--------------------------')
    console.log(JSON.stringify(errorResponse))
    // $this.$message.error(JSON.stringify(errorResponse))
  })
}

/**
 * 获取随机字符串
 * @param len
 * @returns {string}
 * @constructor
 */
Vue.prototype.GetRandomStr = function (len) {
  if (!len) {
    len = 32
  }
  var $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678'
  // 默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1
  var maxPos = $chars.length
  var str = ''
  for (var i = 0; i < len; i++) {
    str += $chars.charAt(Math.floor(Math.random() * maxPos))
  }
  return str
}

Vue.prototype.getPlatform = function () {
  if (typeof (plus) !== 'undefined' && plus.device && plus.device.vendor === 'Apple') {
    return 'iOS'
  } else {
    return 'Android'
  }
}

Vue.prototype.toInt=function (n) {
  if(!n){
    return 0
  }
  n-=0
  n = Math.ceil(n)
  return n - 0
}

/**
 * 获取设备ID
 * @param str
 * @return {number}
 * @constructor
 */
Vue.prototype.GetDeviceID = function () {
  var CurrDeviceID = localStorage.getItem('CurrDeviceID')
  if (!CurrDeviceID) {
    CurrDeviceID = Vue.prototype.GetRandomStr(32)
    localStorage.setItem('CurrDeviceID', CurrDeviceID)
  }
  return CurrDeviceID
}

Vue.prototype.GetFullStyle = function () {
  var winSize = this.getWinSize()
  return {
    width: winSize.width + 'px',
    height: winSize.height + 'px',
  }
}

// 总线程

/* eslint-disable no-new */
function MyVueInit () {
  let bus = new Vue()
  Vue.prototype.bus = bus
  // 初始化Vue
  new Vue({
    el: '#app',
    router,
    components: {App},
    template: '<App/>',
    beforeCreate: function () {
      Vue.prototype.bus = this
    },
    watch: {
      $route: function (to, from) {
        // console.log('to: '+to.name)
        // console.log('是否登录: '+this.CurrUser.IsLogin())
        // console.log('路由变化:')
        // console.log(
        //   [to.path, from.path]
        // )
      }
    }
  })
}

Vue.prototype.getSafeArea()

if (window.location.hostname.indexOf('yangfankj.com')===-1){
  MyVueInit()
}

document.addEventListener('plusready', function () {
  // console.log('plusready')
  if (typeof plus!=='undefined'){
    MyVueInit()
  }
})



/*Vue.directive('keepTwoBits', {
  // 当被绑定的元素插入到 DOM 中时……
  inserted: function (el, binding, vnode) {
    // 聚焦元素
    const numberLength = binding.value || 9
    vnode.componentInstance.$watch('value', function (newValue,oldValue) {
      const index = newValue.indexOf(".");
      // 保留两位
      if (index != -1) {
        const value = newValue.slice(0, index + 3);
        vnode.componentInstance.$emit('input', value)
      }
      const numberLengthArr = [1]
      for(let n = 1; n <= numberLength ; n++){
        numberLengthArr.push(0)
      }
      if(newValue >= +numberLengthArr.join('')) node.componentInstance.$emit('input', oldValue)
    })
  }
})*/


Vue.prototype.checkExpressNumber=function (value) {
  var currStr=value+''
  var regExp = /^[a-zA-Z0-9]{5,50}$/;
  return regExp.test(currStr)
}

Vue.prototype.checkUserName=function (value) {
  var currStr=value+''
  var regExp = /^[a-zA-Z0-9]{2,30}$/;
  return regExp.test(currStr)
}

Vue.prototype.checkShopNumber=function (value) {
  var currStr=value+''
  var regExp = /^[0-9]{8,10}$/;
  return regExp.test(currStr)
}

Vue.prototype.checkName=function (value) {
  var currStr=value+''
  var regExp = /^[\u4E00-\u9FA5A-Za-z0-9]{1,20}$/;
  return regExp.test(currStr)
}

Vue.prototype.checkHotTag=function (value) {
  var currStr=value+''
  var regExp = /^[\u4E00-\u9FA5A-Za-z0-9]{0,10}$/;
  return regExp.test(currStr)
}



window.playVideo=function (node) {
  var _src=node.getAttribute('_src')
  if (typeof plus!=='undefined'){
    if (!window.currVideoPlayer){
      window.currVideoPlayer = new plus.video.VideoPlayer('video',{
        src:_src
      });
    }else{
      window.currVideoPlayer.setOptions({src:_src});
    }
    window.currVideoPlayer.requestFullScreen();
    window.currVideoPlayer.play()
  }
  // alert(node)
}
window.playVideo=function (node) {
  var _src=node.getAttribute('_src')
  if (typeof plus!=='undefined'){
    if (!window.currVideoPlayer){
      window.currVideoPlayer = new plus.video.VideoPlayer('video',{
        src:_src
      });
    }else{
      window.currVideoPlayer.setOptions({src:_src});
    }
    window.currVideoPlayer.requestFullScreen();
    window.currVideoPlayer.play()
  }else{
    alert('暂时只支持app播放')
  }
  // alert(node)
}

